# !/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------
'''
异步迭代器
'''

import asyncio

# 创建迭代器
class Iter(object):
    def __init__(self):
        self.count = 0

    def __aiter__(self):      # 实现异步迭代器用__aiter__，__anext__方法
        return self

    async def func(self):
        self.count += 1
        if self.count == 10:
            return
        return self.count

    async def __anext__(self):     # 放内要用await要用 async
        # 等待func返回数
        ret = await self.func()
        if ret == None:
            raise StopAsyncIteration
        return ret

iter_obj = Iter()     # 创建迭代器对象
async def main():
    async for num in iter_obj:   # async for 需要在异步函数内使用
        print(num)

if __name__ == '__main__':
    asyncio.run(main())
